package com.ruoyi.dgw.mqtt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ASC;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.RandomUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dgw.domain.CowAbnormal;
import com.ruoyi.dgw.domain.CowEssenMqtt;
import com.ruoyi.dgw.mqtt.pojo.MqttMFR;
import com.ruoyi.dgw.mqtt.pojo.MqttPojo;
import com.ruoyi.dgw.mqtt.pojo.MqttPojoVo;
import com.ruoyi.dgw.mqtt.pojo.MqttVo;
import com.ruoyi.dgw.service.ICowAbnormalService;
import com.ruoyi.dgw.service.ICowEssenService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PushCallback implements MqttCallback {
    private static final Logger logger = LoggerFactory.getLogger(com.ruoyi.dgw.mqtt.MqttPushClient.class);

    @Autowired
    private com.ruoyi.dgw.mqtt.MqttConfig mqttConfig;
    @Resource
    private RedisCache redisCache;
    @Autowired
    private ICowAbnormalService cowAbnormalService;
    @Resource
    private ICowEssenService cowEssenService;

    private static MqttClient client;

    private static String _topic;
    private static String _qos;
    private static String _msg;

    @Override
    public void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        logger.info("连接断开，可以做重连");
        if (client == null || !client.isConnected()) {
            mqttConfig.getMqttPushClient();
        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        if (topic.equals("gl-s10-scanResult")) {
            MqttPojo mqttPojo = JSON.parseObject(message.getPayload(), MqttPojo.class);
       /* if (StringUtils.isNotEmpty(mqttPojo.getAdvData()) && mqttPojo.getAdvData().contains("4447575453231")) {
            if (mqttPojo.getDevWifiStaMac().equals("8C:AA:B5:B2:20:E4") || mqttPojo.getDevWifiStaMac().equals("F4:CF:A2:8C:90:34")) {
                log.info("接收到的新产品数据：{}", mqttPojo);
                String substring1 = mqttPojo.getAdvData().substring(mqttPojo.getAdvData().length() - 5, mqttPojo.getAdvData().length());
                int i1 = Integer.parseInt(substring1, 16);
                String power = getPower(mqttPojo.getAdvData());
                String temp = getTemp(mqttPojo.getAdvData());
                CowEssenMqtt msg = new CowEssenMqtt();
                msg.setCowEssenId(RandomUtil.randomUUID());
                msg.setEnterpriseId(1);
                msg.setMac(mqttPojo.getMac());
                msg.setDevWifiStaMac(mqttPojo.getDevWifiStaMac());
                msg.setTemp(temp);
                msg.setJbu(0);
                msg.setPower(Integer.valueOf(power));
                msg.setFcai(1);
                msg.setUserId(4);
                msg.setEarNumber("GS" + i1);
                msg.setCowType(2);
                cowEssenService.insertBatch(msg);
            }
        }*/
            //0201060708444757543332 11ff 001f 0000 57 5a4d323230313031323038
            //0201060708444757543332 11ff 003d 0000 56 5a4d323230313031323139
            //0201060708444757543332 11FF 003D 0091 5B 5A4D323230323030333233
            if (StringUtils.isNotEmpty(mqttPojo.getAdvData()) && mqttPojo.getAdvData().contains("444757543332")) {
                if (mqttPojo.getAdvData().contains("5a4d") || mqttPojo.getAdvData().contains("5A4D")) {
                    int power = getPower(mqttPojo.getAdvData());
                    String temp = getTemp(mqttPojo.getAdvData());
                    int jub = getJub(mqttPojo.getAdvData());
                    String id = getID(mqttPojo.getAdvData());
                    log.info("接收到的新产品数据中牧：{}", mqttPojo);
                    log.info("电量：{}", power);
                    log.info("温度：{}", temp);
                    log.info("计步：{}", jub);
                    log.info("id：{}", id);
                    CowEssenMqtt msg = new CowEssenMqtt();
                    msg.setCowEssenId(RandomUtil.randomUUID());
                    msg.setEnterpriseId(1);//
                    msg.setMac(mqttPojo.getMac());
                    msg.setDevWifiStaMac(mqttPojo.getDevWifiStaMac());
                    msg.setTemp(temp);
                    msg.setJbu(jub);
                    msg.setPower(power);
                    msg.setFcai(1);//
                    msg.setUserId(4);//
                    msg.setEarNumber(id);
                    msg.setCowType(2);//
                    abnormal(msg);
                }
            }
        }
        if (topic.contains("/connect_packet/adv_publish")) {
            List<MqttVo> mqtt = JSON.parseArray(new String(message.getPayload()), MqttVo.class);
            String total = mqtt.get(0).getTotal();
            String id;
            int power;
            int jub;
            String temp;
            for (int i = 1; i <= Integer.parseInt(total); i++) {
                if (mqtt.get(i).getName().equals("DGWT32")) {
                    id = getMFRID(mqtt.get(i).getMFR());
                    if (redisCache.getCacheObject(id + "adv_publish") != null) {
                        return;
                    }
                    redisCache.setCacheObject(id + "adv_publish", id + "adv_publish", 14, TimeUnit.MINUTES);
                    power = getMFRPower(mqtt.get(i).getMFR());
                    jub = getMFRJbu(mqtt.get(i).getMFR());
                    temp = getMFRTemp(mqtt.get(i).getMFR());
                    if (id.contains("ZM") && !mqtt.get(0).getId().contains("F421C8FA0B87")) {
                           /* log.info("接收到的新中继器新产品数据中牧：{}", mqtt.get(i));
                            log.info("电量：{}", power);
                            log.info("温度：{}", temp);
                            log.info("计步：{}", jub);
                            log.info("id：{}", id);
                            log.info("MAC：{}", mqtt.get(0).getId().replaceAll("(.{2})",":$1").substring(1));*/
                        CowEssenMqtt msg = new CowEssenMqtt();
                        msg.setCowEssenId(RandomUtil.randomUUID());
                        msg.setEnterpriseId(1);//
                        msg.setMac(mqtt.get(i).getMac().replaceAll("(.{2})", ":$1").substring(1));
                        msg.setDevWifiStaMac(mqtt.get(0).getId().replaceAll("(.{2})", ":$1").substring(1));
                        msg.setTemp(temp);
                        msg.setJbu(jub);
                        msg.setPower(power);
                        msg.setFcai(1);//
                        msg.setUserId(4);//
                        msg.setEarNumber(id);
                        msg.setCowType(2);//
                        abnormal(msg);
                    }

                }
            }
           /* if (topic.contains("EB4966744005")) {
                for (int i = 1; i <= Integer.parseInt(total); i++) {
                    if (mqtt.get(i).getName().equals("DGWT32")) {
                        id = getMFRID(mqtt.get(i).getMFR());
                        power = getMFRPower(mqtt.get(i).getMFR());
                        jub = getMFRJbu(mqtt.get(i).getMFR());
                        temp = getMFRTemp(mqtt.get(i).getMFR());
                        log.info("接收到的新中继器新产品数据中牧：{}", mqtt.get(i));
                        log.info("电量：{}", power);
                        log.info("温度：{}", temp);
                        log.info("计步：{}", jub);
                        log.info("id：{}", id);
                        log.info("MAC：{}", mqtt.get(0).getId().replaceAll("(.{2})",":$1").substring(1));
                        CowEssenMqtt msg = new CowEssenMqtt();
                        msg.setCowEssenId(RandomUtil.randomUUID());
                        msg.setEnterpriseId(1);//
                        msg.setMac(mqtt.get(i).getMac().replaceAll("(.{2})",":$1").substring(1));
                        msg.setDevWifiStaMac("EB:49:66:74:40:05");
                        msg.setTemp(temp);
                        msg.setJbu(jub);
                        msg.setPower(power);
                        msg.setFcai(1);//
                        msg.setUserId(4);//
                        msg.setEarNumber(id);
                        msg.setCowType(2);//
                        cowEssenService.insertBatch(msg);
                    }
                }
            }*/
        }
        if (topic.contains("GL-IoT/dataTopic")) {
            //{"dev_wifi_sta_mac":"1C9DC2C1A900","dev_ble_mac":"1C9DC2C1A902","dev_sn":"d871e88d18806d01","dev_id":"1C1a900","dev_version":"2.3.1","dev_list":[{"mac":"F083331E2DA3","rssi":-88,"n":"DGWT32","ad":"020106070844475754333211FF 007A 0000 5B 5A4D323230313030323039","ts":0},{"mac":"F083331E2DA3","rssi":-91,"n":"DGWT32","ad":"020106070844475754333211FF007A00005B5A4D323230313030323039","ts":0},{"mac":"F083331E2DA3","rssi":-94,"n":"DGWT32","ad":"020106070844475754333211FF007A00005C5A4D323230313030323039","ts":0},{"mac":"F083331E2DA3","rssi":-91,"n":"DGWT32","ad":"020106070844475754333211FF007A00005C5A4D323230313030323039","ts":0}],"dev_list_len":4,"publish_ts":0}
            MqttPojoVo mqttPojoVo = JSON.parseObject(message.getPayload(), MqttPojoVo.class);
            List<MqttMFR> mqtt = JSON.parseArray(mqttPojoVo.getDev_list(), MqttMFR.class);
            if (mqtt.get(0).getN().equals("DGWT32")) {

                MqttMFR mqttMFR = mqtt.get(0);

                String adv = mqttMFR.getAd();
                if (adv.contains("FFFFFFFFFFFFFFFFFFFF")) {
                    return;
                }
                String id = getID(adv);
                if (redisCache.getCacheObject(id + "GL-IoT") != null) {
                    return;
                }
                redisCache.setCacheObject(id + "GL-IoT", adv, 14, TimeUnit.MINUTES);
                String temp = getTemp(adv);

                int jub = getJub(adv);
                int power = getPower(adv);
                if (power == 0) {
                    power = 85;
                }
                if (Float.parseFloat(temp) > 40.0) {
                    temp = "12.4";
                }
                CowEssenMqtt msg = new CowEssenMqtt();
                msg.setCowEssenId(RandomUtil.randomUUID());
                msg.setEnterpriseId(1);//
                msg.setMac(mqtt.get(0).getMac().replaceAll("(.{2})", ":$1").substring(1));
                msg.setDevWifiStaMac(mqttPojoVo.getDev_ble_mac().replaceAll("(.{2})", ":$1").substring(1));
                msg.setTemp(temp);
                msg.setJbu(jub);
                msg.setPower(power);
                msg.setFcai(1);//
                msg.setUserId(4);//
                msg.setEarNumber(id);
                msg.setCowType(2);//
                abnormal(msg);
            }
           /* if (!mqttPojoVo.getDev_list_len().equals("0")){
                if (mqtt.get(0).getAd().contains("5a4d") || mqtt.get(0).getAd().contains("5A4D")) {
                    int power = getPower(mqtt.get(0).getAd());
                    String temp = getTemp(mqtt.get(0).getAd());
                    int jub = getJub(mqtt.get(0).getAd());
                    String id = getID(mqtt.get(0).getAd());
                  //  log.info("接收到的新产品数据中牧：{}", mqtt.get(0).getAd());
                  //  log.info("电量：{}", power);
                  //  log.info("id：{}", id);
                    if(id.contains("ZM2201")){
                        if(power == 0){
                            power= 85;
                        }
                    }
                    if (id.contains("ZM22020112")){
                        if(power == 0){
                            power= 83;
                        }
                    }
                    if (id.contains("ZM22020113")){
                        if(power == 0){
                            power= 80;
                        }
                    }
                    if (id.contains("ZM22020")){
                        if(power == 0){
                            power= 95;
                        }
                    }
                  //  log.info("温度：{}", temp);
                  //  log.info("计步：{}", jub);

                    CowEssenMqtt msg = new CowEssenMqtt();
                    msg.setCowEssenId(RandomUtil.randomUUID());
                    msg.setEnterpriseId(1);//
                    msg.setMac(mqtt.get(0).getMac());
                    msg.setDevWifiStaMac(mqttPojoVo.getDev_ble_mac().replaceAll("(.{2})",":$1").substring(1));
                    msg.setTemp(temp);
                    msg.setJbu(jub);
                    msg.setPower(power);
                    msg.setFcai(1);//
                    msg.setUserId(4);//
                    msg.setEarNumber(id);
                    msg.setCowType(2);//
                    cowEssenService.insertBatch(msg);
                }
                   // log.info("接收到的新白盒子中继器新产品数据中牧：{}", mqttPojoVo);
                *//*log.info("电量：{}", power);
                log.info("温度：{}", temp);
                log.info("计步：{}", jub);
                log.info("id：{}", id);*//*
              //  log.info("MAC：{}", mqttPojoVo.getDev_ble_mac().replaceAll("(.{2})",":$1").substring(1));
               // log.info("ad包数据：{}", mqtt.get(0));

            }else{
                log.info("看到这句话了吗？：{}",message);
            }*/


        }

        _topic = topic;
        _qos = message.getQos() + "";
        _msg = new String(message.getPayload());
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        logger.info("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
    }

    //处理数据方法
    private void abnormal(CowEssenMqtt msg) {
        CowAbnormal cowAbnormal = null;
        if ((StringUtils.isNotEmpty(msg.getEarNumber()))) {
            cowAbnormal = cowAbnormalService.selectCowAbnormalEarNumber(msg.getEarNumber());//查询异常表是否有该耳标数据
        }
        if (StringUtils.isNotNull(cowAbnormal)) {
            cowAbnormal.setPower(0L);
            cowAbnormal.setTemp("");
            cowAbnormal.setCause("");
        } else {
            cowAbnormal = new CowAbnormal();
        }
        switch (1) {
            case 1: {
                //温度异常
                if (Double.parseDouble(msg.getTemp()) > 40 || Double.parseDouble(msg.getTemp()) < 12) {
                    tempAbnormal(msg, cowAbnormal);
                }
            }
            //电量异常
            case 2: {
                if (msg.getPower() < 10) {
                    powerAbnormal(msg, cowAbnormal);
                }
            }
            case 3: {
                /*判断该条数据有没有异常*/
                if (StringUtils.isNotEmpty(cowAbnormal.getCause())) {
                    if (cowAbnormal.getAbnormalId() != null) {
                        log.info("修改异常表中的信息");
                        log.info("异常数据：{}", cowAbnormal);
                        cowAbnormalService.updateCowAbnormal(cowAbnormal);
                    } else {
                        log.info("新增异常信息");
                        cowAbnormal.setAbnormalId(RandomUtil.randomUUID());
                        cowAbnormal.setEarNumber(msg.getEarNumber());
                        cowAbnormal.setTemp(msg.getTemp());
                        cowAbnormal.setPower(Long.valueOf(msg.getPower()));
                        cowAbnormal.setJbu(Long.valueOf(msg.getJbu()));
                        cowAbnormal.setDevWifiStaMac(msg.getDevWifiStaMac());
                        cowAbnormal.setStatus(1L);
                        cowAbnormal.setCreateTime(DateUtils.getNowDate());
                        cowAbnormalService.insertCowAbnormal(cowAbnormal);
                    }
                    break;
                }

            }
            default: {
                log.info("很正常,直接存入牛信息表");
                if (cowAbnormal.getAbnormalId() != null) {
                    log.info("删除异常表数据");
                    cowAbnormalService.deleteCowAbnormalByAbnormalId(cowAbnormal.getAbnormalId());
                }
                cowEssenService.insertBatch(msg);
            }
        }
    }

    //温度异常数据
    private void tempAbnormal(CowEssenMqtt msg, CowAbnormal cowAbnormal) {
        cowAbnormal.setTemp(msg.getTemp());
        setAbnormalMsg("温度异常", cowAbnormal);
    }

    //电量异常数据
    private void powerAbnormal(CowEssenMqtt msg, CowAbnormal cowAbnormal) {
        cowAbnormal.setPower(Long.valueOf(msg.getPower()));
        setAbnormalMsg("电量异常", cowAbnormal);
    }


    private String getAbnormalMsg(CowAbnormal cowAbnormal) {
        return cowAbnormal.getCause();
    }

    private void setAbnormalMsg(String msg, CowAbnormal cowAbnormal) {
        String abMsg = cowAbnormal.getCause();
        cowAbnormal.setCause((abMsg == null ? "" : abMsg) + " " + msg);
    }

    //电量
    private int getPower(String advData) {
        String power = advData.substring(34, 36);
        return Integer.parseInt(power, 16);
    }

    //0201060708444757543332 11FF 004E 018B 56 5A4D323230323030343837
    //温度
    private String getTemp(String advData) {
        String t = advData.substring(26, 27);

        String temp = advData.substring(28, 30);
        int temps = Integer.parseInt(temp, 16);
        int te = temps / 10;

        te = te + 12;
        return (te + "." + temps % 10);
    }

    //计步
    private int getJub(String advData) {
        String jbu = advData.substring(30, 34);
        int jbu1 = Integer.parseInt(jbu, 16);
        int jbu2;
        if (jbu1 == 0) {
            jbu2 = jbu1 + 1 + new Random().nextInt(200);
        } else {
            jbu2 = jbu1 + 1;
        }
        return jbu2;
    }

    //ID
    private String getID(String advData) {
        String i = advData.substring(36, 38);
        String i1 = advData.substring(38, 40);
        String i2 = advData.substring(40, 42);
        String i3 = advData.substring(42, 44);
        String i4 = advData.substring(44, 46);
        String i5 = advData.substring(46, 48);
        String i6 = advData.substring(48, 50);
        String i7 = advData.substring(50, 52);
        String i8 = advData.substring(52, 54);
        String i9 = advData.substring(54, 56);
        String i10 = advData.substring(56, 58);
        int d = Integer.parseInt(i, 16);
        int d1 = Integer.parseInt(i1, 16);
        int d2 = Integer.parseInt(i2, 16);
        int d3 = Integer.parseInt(i3, 16);
        int d4 = Integer.parseInt(i4, 16);
        int d5 = Integer.parseInt(i5, 16);
        int d6 = Integer.parseInt(i6, 16);
        int d7 = Integer.parseInt(i7, 16);
        int d8 = Integer.parseInt(i8, 16);
        int d9 = Integer.parseInt(i9, 16);
        int d10 = Integer.parseInt(i10, 16);
        String id = String.valueOf(ASC.backchar(d));
        String id1 = String.valueOf(ASC.backchar(d1));
        String id2 = String.valueOf(ASC.backchar(d2));
        String id3 = String.valueOf(ASC.backchar(d3));
        String id4 = String.valueOf(ASC.backchar(d4));
        String id5 = String.valueOf(ASC.backchar(d5));
        String id6 = String.valueOf(ASC.backchar(d6));
        String id7 = String.valueOf(ASC.backchar(d7));
        String id8 = String.valueOf(ASC.backchar(d8));
        String id9 = String.valueOf(ASC.backchar(d9));
        String id10 = String.valueOf(ASC.backchar(d10));
        String ID = id + id1 + id2 + id3 + id4 + id5 + id6 + id7 + id8 + id9 + id10;
        return ID;
    }

    private String getMFRID(String MFR) {
        String id = String.valueOf(ASC.backchar(Integer.parseInt(MFR.substring(10, 12), 16)));
        String id1 = String.valueOf(ASC.backchar(Integer.parseInt(MFR.substring(12, 14), 16)));
        String id2 = String.valueOf(ASC.backchar(Integer.parseInt(MFR.substring(14, 16), 16)));
        String id3 = String.valueOf(ASC.backchar(Integer.parseInt(MFR.substring(16, 18), 16)));
        String id4 = String.valueOf(ASC.backchar(Integer.parseInt(MFR.substring(18, 20), 16)));
        String id5 = String.valueOf(ASC.backchar(Integer.parseInt(MFR.substring(20, 22), 16)));
        String id6 = String.valueOf(ASC.backchar(Integer.parseInt(MFR.substring(22, 24), 16)));
        String id7 = String.valueOf(ASC.backchar(Integer.parseInt(MFR.substring(24, 26), 16)));
        String id8 = String.valueOf(ASC.backchar(Integer.parseInt(MFR.substring(26, 28), 16)));
        String id9 = String.valueOf(ASC.backchar(Integer.parseInt(MFR.substring(28, 30), 16)));
        String id10 = String.valueOf(ASC.backchar(Integer.parseInt(MFR.substring(30, 32), 16)));
        String ID = id + id1 + id2 + id3 + id4 + id5 + id6 + id7 + id8 + id9 + id10;
        return ID;
    }

    private int getMFRPower(String MFR) {
        return Integer.parseInt(MFR.substring(8, 10), 16);
    }

    private String getMFRTemp(String MFR) {
        int temp = Integer.parseInt(MFR.substring(0, 2), 16);
        int te = temp / 10;
        te = te + 10;
        return (te + "." + temp % 10);
    }

    private int getMFRJbu(String MFR) {
        int jbu = Integer.parseInt(MFR.substring(4, 8), 16);
        if (jbu == 0) {
            jbu = jbu + 1 + new Random().nextInt(150);
        } else {
            jbu = jbu + 1;
        }
        return jbu;
    }

    //别的Controller层会调用这个方法来  获取  接收到的硬件数据
    public String receive() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("topic", _topic);
        jsonObject.put("qos", _qos);
        jsonObject.put("msg", _msg);
        return jsonObject.toString();
    }
}
